<?php

namespace app\merchant\service;

use app\merchant\model\Address;
use app\merchant\model\Order;
use app\merchant\model\User;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use think\facade\Filesystem;
use Vtiful\Kernel\Excel;
use app\Response;

class OrderService
{
    public static function orderListService($m_uid,$page,$num,$post_num,$state,$start_time,$end_time){
        $where[] = ["uid","=",$m_uid];
        if(!empty($post_num)){
            if(ctype_digit($post_num)){
                if(!empty($post_num)){
                    $where[] = ["o_number","=",$post_num];
                }
            }else{
                preg_match_all('/\d+/', $post_num, $numbers); // 匹配数字
                preg_match_all('/[A-Za-z]+/', $post_num, $letters); // 匹配字母
                if(!empty($numbers)){
                    $o_number = $numbers[0][0];
                    $where[] = ["o_number","=",$o_number];
                }
                if(!empty($letters)){
                    $letters = $letters[0][0];
                    $where[] = ["prefix","like","%".$letters."%"];
                }
            }
        }
        if (is_numeric($state)){
            $where[] = ["state","=",(int)$state];
        }
        if(!empty($start_time)){
            $startTime = strtotime($start_time);
            $where[] = ["addtime",">=",$startTime];
        }
        if (!empty($end_time)){
            $endTime = strtotime($end_time)+86400;
            $where[] = ["addtime","<=",$endTime];
        }
        $order_list = Order::dataList($where,$page,$num);
        if (!empty($order_list)){
            $data = $order_list->toArray();
            foreach($data as $k=>$v){
                $data[$k]["retime"] = !empty($v["retime"])?date("Y-m-d H:i:s",$v["retime"]):"";
                $data[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = Order::dataCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }



    /***
     * 订单修改
     */
    public static function orderEditService($oId,$m_uid,$state){
        //   状态 1已录入 2已到网点  4已送达 6已结算
        $oInfo = Order::dataView(["id"=>$oId,"uid"=>$m_uid]);
        if(!$oInfo){
            return Response::wrapError(0,"未查询到当前订单!");
        }
        switch ($state){
            case 6:
                $data = ["state"=>6,"overtime"=>time()];
                break;
            default:
                $data = ["state"=>$state];
                break;
        }
        $res = Order::dataEdit(["id"=>$oId],$data);
        if ($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }

    /****
     * 订单批量操作
     */
    public static function orderBatchEditService($m_uid,$oIds,$state){
        if(empty($oIds)){
            return Response::wrapError(0,"参数异常!");
        }
        if(is_array($oIds)){
            $oIds = implode(",",$oIds);
        }
        switch ($state){
            case 6:
                $data = ["state"=>6,"overtime"=>time()];
                break;
            default:
                $data = ["state"=>$state];
                break;
        }
        $where[] = ["id","in",$oIds];
        $where[] = ["uid","=",$m_uid];
        $res = Order::dataEdit($where,$data);
        if ($res){
            Log::record('商家ID:'.$m_uid.' 批量操作订单'.json_encode($oIds,JSON_UNESCAPED_UNICODE));
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }



    public static function orderImportService($m_uid,$file){
        try {
           validate(['file'=>'filesize:102400|fileExt:xls'])
            ->check([$file]);
        }catch (ValidateException $e){
            return Response::wrapError($file->getError(),-1);
        }
        $userInfo = User::userInfo(["uid"=>$m_uid]);
        if(empty($userInfo)){
            return Response::wrapError(-200,"登录信息异常!");
        }
        $savename = Filesystem::disk('public')->putFile( 'uploads/excel_upload', $file);
        $filepath = app()->getRootPath() . 'public';
        $filepath = str_replace("\\",'/',$filepath);
        $config = [
            'path' => $filepath// xlsx文件保存路径
        ];
        $save_name = str_replace("\\",'/',$savename);
        $excel  = new \Vtiful\Kernel\Excel($config);
        $data = $excel->openFile($save_name)
            ->openSheet('Sheet1', \Vtiful\Kernel\Excel::SKIP_EMPTY_CELLS)
            ->setSkipRows(1)
            ->getSheetData();
        $list = array_filter($data,"isNotEmpty");
        $addressList = Address::datalistAll(["uid"=>$m_uid,"enable"=>1]);
        if(!empty($addressList)){
            foreach ($addressList as $k => $v){
                Cache::set($v["shop"].$v["platform"].$v["address"].$v["phone"],json_encode($v),120);
            }
        }
        $add_data = [];
        if(!empty($list)){
            $time = time();
            foreach ($list as $k=>$v){
                if(!empty($v[0])&!empty($v[1])&!empty($v[2])&!empty($v[3])){
                    if(ctype_digit($v[0])){
                        $add_data[$k]["o_number"] = $v[0];
                        $add_data[$k]["prefix"] = "";
                    }else{
                        preg_match_all('/\d+/', $v[0], $numbers); // 匹配数字
                        preg_match_all('/[A-Za-z]+/', $v[0], $letters); // 匹配字母
                        if(!empty($numbers)){
                            $o_number = $numbers[0][0];
                            $add_data[$k]["o_number"] = $o_number;
                        }
                        if(!empty($letters)){
                            $letters = $letters[0][0];
                            $add_data[$k]["prefix"] = $letters;
                        }
                    }
                    $add_data[$k]["uid"] = $m_uid;
                    $add_data[$k]["state"] = 1;
                    $add_data[$k]["paid"] = $userInfo["paid"];
                    if(Cache::has($v[2].$v[3].$v[7].$v[8])){
                        $add[$k]["address_info"] = Cache::get($v[2].$v[3].$v[7].$v[8]);
                        $add[$k]["address"] = (array)json_decode($add[$k]["address_info"]);;
                        $add_data[$k]["address_info"] = (array)json_decode($add[$k]["address_info"]);
                        $add_data[$k]["significant"] = $add[$k]["address"]["significant"];
                    }
                    $add_data[$k]["addtime"] = $time;
                }else{
                    continue;
                }

            }
            if(!empty($add_data)){
                Db::startTrans();
                try {
                    Order::dataAddAll($add_data);
                    Db::commit();
                    return Response::wrapData();
                }catch (\Exception $e) {
                    Db::rollback();
                    return Response::wrapError(0,"导入失败,请按表头及合作信息列表地址信息将表格填写完整!");
                }
            }
        }
        return Response::wrapError(0,"未读取到有效数据!");
    }

    public static function orderExcelExportService($state,$start_time,$end_time,$m_uid){
        $userInfo = User::userInfo(["uid"=>$m_uid]);
        if(empty($userInfo)){
            return Response::wrapError(-200,"登录信息异常!");
        }
        $where[] = ["o.uid","=",$userInfo["uid"]];
        $where[] = ["o.paid","=",$userInfo["paid"]];
        if(is_numeric($state)){
            $where[] = ["o.state","=",$state];
        }
        if(!empty($start_time)){
            $startTime = strtotime($start_time);
            $where[] = ["o.addtime",">=",$startTime];
        }
        if (!empty($end_time)){
            $endTime = strtotime($end_time)+86400;
            $where[] = ["o.addtime","<=",$endTime];
        }
        $storeName = User::userInfo(["uid"=>$userInfo["paid"]])["nickname                                                            "];
        $data = Order::dataListJoinAll($where,$field="o.id,o.prefix,o.o_number,o.addtime,o.state,o.overtime,u.phone");

        if($data){
            $list = $data;
            $info = [];
            foreach($list as $k=>$v){
                $info[$k]["post_num"] = !empty($v["prefix"])?$v["prefix"].$v["o_number"]:$v["o_number"];
                $info[$k]["m_phone"] = !empty($v["phone"])?$v["phone"]:0;
                switch ($v["state"]){
                    case 1:
                        $info[$k]["state_str"] = "已录入";
                        break;
                    case 2:
                        $info[$k]["state_str"] = "已到网点";
                        break;
                    case 4:
                        $info[$k]["state_str"] = "已送达";
                        break;
                    case 6:
                        $info[$k]["state_str"] = "已结算";
                        break;
                }
                $info[$k]["storeName"] = $storeName;
                $info[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
                $info[$k]["overtime"] = !empty($v["overtime"])?date("Y-m-d H:i:s",$v["overtime"]):"";
            }
        }else{
            return Response::wrapError(0,  "暂无数据！");
        }
        $config = [
            'path' =>Config::get('mapping.xslwriter_path').'uploads/xlsx' // xlsx文件保存路径
        ];
        $excel  = new Excel($config);
        $excelName = "订单列表".time();
        $filePath = $excel->fileName($excelName.'.xlsx', 'sheet1')
            ->header(["快递单号","商家手机号","订单状态","网点名称","录入时间","结算时间"])
            ->data($list)
            ->output();
        if ($filePath){
            return Response::wrapData(["path"=>'uploads/xlsx/'.$excelName.'.xlsx']);
        }else{
            return Response::wrapError(0,"导出失败!");
        }

    }
}